package com.esp.app.gps;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;

import com.esp.app.widget.R;


public class ViewGpsHandler{
	
	private static final String TAG = ViewGpsHandler.class.getName();
	public static Context mContext;
	public static void updateAppWidgets(final Context context,
			final AppWidgetManager appWidgetManager, final int[] appWidgetIds,
			final int resource) {
		
		mContext = context;
		Log.d(TAG, " ViewGpsHandler|=> updateAppWidgets() ");
		for (int i = 0; i < appWidgetIds.length; i++) {
			final int appWidgetId = appWidgetIds[i];
			updateAppWidget(context, appWidgetManager, appWidgetId, resource);
		}
	}

	public static void updateAppWidget(final Context context,
			final AppWidgetManager appWidgetManager, final int appWidgetId,
			final int resource) {

		Log.d(TAG, " ViewGpsHandler|=> updateAppWidget() ");
		final RemoteViews views = new RemoteViews(context.getPackageName(),
				R.layout.widget_layout);
		views.setImageViewResource(R.id.btn_gps,resource);
		
		// start gps setting 
		Intent gpsIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		PendingIntent pendingGpsIntent = PendingIntent.getActivity(context, 0, gpsIntent, PendingIntent.FLAG_CANCEL_CURRENT);
		views.setOnClickPendingIntent(R.id.btn_gps, pendingGpsIntent);
		
		appWidgetManager.updateAppWidget(appWidgetId, views);
		
		LocationManager lm = (LocationManager)context.getSystemService(context.LOCATION_SERVICE);
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,300000,1,mLocationListner);	
	      
	}
	
	public static LocationListener mLocationListner = new LocationListener() {
		
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
		
		public void onProviderEnabled(String provider) {
		}
		
		public void onProviderDisabled(String provider) {
			
			
			/* this is called if/when the GPS is disabled in settings */
			Log.v(TAG, " onProviderDisabled ");
			Intent intent = new Intent();
	 		intent.setAction(GpsModel.GPS_CHANGED_ACTION);
	 		mContext.sendBroadcast(intent);
	 	
		}
		
		public void onLocationChanged(Location location) {
		}
	};
	
	  
}
